/*
 * @Author: 晟松
 * @Date: 2021-12-14 21:07:59
 * @LastEditors: 晟松
 * @LastEditTime: 2022-03-09 17:02:56
 * @FilePath: \mini-vue3d:\Code\node\koa2\volunteer-service\src\main\service\MessageService.js
 * @Description:
 */

import sequelize from "@main/db";
import { isNull, isBlank } from "@main/util/ValidateUtil";
import { ParamError, LoginError, NotFoundError } from "@main/common/CommonError";
import { encryptPassword, checkPassword } from "@main/util/PasswordUtil";
import config from "@main/config";
import blacklist from "blacklist";
import whiteListed from "whitelisted";
import jwt from "jsonwebtoken";
import enums from "@main/config/enums";
import { toEnumNum, toEnumStr } from "@main/util/EnumsUtil";
import whitelisted from "whitelisted";
import Web3Service from "./Web3Service";

// 获取所有定义的model
const models = sequelize.models;

class MessageService {
    /**
     * @description: 获得自己相关的消息
     * @param {*} params
     * @return {*}
     */
    static async getMineMessage(user, params) {
        let { identity } = user;
        // 获取对应用户表中的数据
        user = user[identity];
        let { id } = user;
        console.log("getMineMessage user: ", user);
        // 获得一对一消息，主要是居委会对居民发起的志愿服务的打回、确认这些
        let oneMessage = await models["message"].findAll({
            where: {
                toId: id,
                toIdentity: toEnumNum(identity, "identity"),
            },
        });

        // 获取自己所属的管理员的信息，方便从全局信息里获取，只针对学生和居民
        let fromId, fromIdentity;
        if (identity == "student") {
            fromId = user.schoolId;
            fromIdentity = enums.identity["school"];
        } else if (identity == "resident") {
            fromId = user.communityId;
            fromIdentity = enums.identity["community"];
        } else {
            fromId = -1;
            fromIdentity = -1;
        }

        // 获得自己居委会或者自己学校发的所有全体消息
        let globalMessage = await models["globalMessage"].findAll({
            where: {
                fromId,
                fromIdentity,
                isPublic: false,
            },
        });
        // 获得所有的全体信息，即系统消息
        let systemMessage = await models["globalMessage"].findAll({
            where: {
                isPublic: true,
            },
        });
        // 将发送者的身份加到数据上面去
        for (let i = 0; i < oneMessage.length; i++) {
            oneMessage[i].dataValues.fromUser = await models[toEnumStr(oneMessage[i].fromIdentity, "identity")].findOne({
                where: {
                    id: oneMessage[i].dataValues.fromId,
                },
            });
        }

        for (let i = 0; i < globalMessage.length; i++) {
            globalMessage[i].dataValues.fromUser = await models[toEnumStr(globalMessage[i].fromIdentity, "identity")].findOne({
                where: {
                    id: globalMessage[i].fromId,
                },
            });
        }
        for (let i = 0; i < systemMessage.length; i++) {
            systemMessage[i].dataValues.fromUser = await models[toEnumStr(systemMessage[i].fromIdentity, "identity")].findOne({
                where: {
                    id: systemMessage[i].fromId,
                },
            });
        }
        // 不能在map中使用异步，不会获取到数据的
        // systemMessage = systemMessage.map(async function(message){
        //     message.fromUser =await models[toEnumStr(message.fromIdentity,'identity')].findOne({
        //         where:{
        //             id:message.fromId
        //         }
        //     })
        //     return message
        // })

        return { oneMessage, globalMessage, systemMessage };
    }

    /**
     * @description: 辅导员或者居委会获取自己所发送的消息
     * @param {*} user
     * @param {*} params
     * @return {*}
     */
    static async getMineMessageList(user, params) {
        let { id: fromId, identity: fromIdentity } = user;

        let oneMessage = await models["message"].findAll({
            where: {
                fromId,
                fromIdentity,
            },
        });

        let globalMessage = await models["globalMessage"].findAll({
            where: {
                fromId,
                fromIdentity,
                isPublic: false,
            },
        });
        // 获得所有的全体信息
        let systemMessage = await models["globalMessage"].findAll({
            where: {
                isPublic: true,
            },
        });
        // 将发送者的身份加到数据上面去
        for (let i = 0; i < oneMessage.length; i++) {
            oneMessage[i].dataValues.toUser = await models[toEnumStr(oneMessage[i].toIdentity, "identity")].findOne({
                where: {
                    id: oneMessage[i].dataValues.toId,
                },
            });
        }
        let allMessageList = [...oneMessage, ...globalMessage, ...systemMessage];
        return { oneMessage, globalMessage, systemMessage, allMessageList };
    }

    /**
     * @description: 通过id获取message信息
     * @param {*} isPublic 主要是通过这个是否存在，存在的值判断是单独消息还是全体消息这些
     * @return {*}
     */
    static async getOneMessage(params) {
        let { messageId, isPublic } = params;
        console.log("params: ", params);
        let res = {};
        // 判断是否不为空，即为true或false这种情况
        if (!isBlank(isPublic)) {
            res = await models["globalMessage"].findOne({
                where: {
                    id: messageId,
                    isPublic,
                },
            });
        } else {
            res = await models["message"].findOne({
                where: {
                    id: messageId,
                },
            });
        }

        res.dataValues.fromUser = await models[toEnumStr(res.fromIdentity, "identity")].findOne({
            where: {
                id: res.fromId,
            },
        });
        return res;
    }
    /**
     * @description: 单个用户发送一条消息给单个用户
     * @param {*} params
     * @return {*}
     */
    static async addOneMessage(params) {
        let { id: fromId, identity: fromIdentity, toIdentity } = params;
        fromIdentity = toEnumNum(fromIdentity, "identity");
        toIdentity = toEnumNum(toIdentity, "identity");

        let message = whitelisted(params, ["title", "message", "isPublic", "toId"]);
        Object.assign(message, { fromId, fromIdentity, toIdentity });
        let res = await models["message"].create(message);

        await Web3Service.updateOne("message", res.id);
        return res;
    }

    /**
     * @description: 发送一类消息，如辅导员发给自己的所有学生
     * @param {*} params
     * @return {*}
     */
    static async addGlobalMessage(params) {
        let { id: fromId, identity: fromIdentity } = params;
        fromIdentity = toEnumNum(fromIdentity, "identity");
        let globalMessage = whitelisted(params, ["title", "message", "isPublic"]);
        Object.assign(globalMessage, { fromId, fromIdentity });
        let res = await models["globalMessage"].create(globalMessage);

        await Web3Service.updateOne("globalMessage", res.id);
        return res;
    }
}

export default MessageService;
